Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

272
Visualizações
creating functionality for element to stop "setInterval" function (triggered by another element)

I have created an automatic slideshow - which starts after clicking "menu item". I'm looking for a way to "turn it off", when clicking different "menu item". The whole problem can be abstracted to a simple example:

Constructing functionality for "stop" <li> (that would probably utilize stopInterval). I can't come up with a solution, would anyone have an idea ?

const li1 = document.getElementById("li1")

li1.addEventListener("click", slideShowAbstract)

function slideShowAbstract(e) {

    const y = setInterval(()=> console.log("playing"), 2000)

    }
ul {
    display: flex;
    justify-content: center;
    list-style-type: none;
  }
  
li {
    margin: 1rem;
}

li:hover {
    cursor: pointer;
}
            <ul>
                <li id="li1">play</li>
                <li id="li2">stop</li>
            </ul>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can declare the y outside so that you can access it from multiple handlers.

const li1 = document.getElementById("li1")
const stopElement = document.getElementById("stopButton")
let intervalTimer;

li1.addEventListener("click", slideShowAbstract);
stopElement.addEventListener('click', stopSlideShow);


function slideShowAbstract(e) {
  intervalTimer = setInterval(() => console.log("playing"), 2000);
}

function stopSlideShow(){
  clearInterval(intervalTimer);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

a better way ?

to avoid having global variables that can be jostled by side effects, use an object, to which you can add your useful methods.

const 
  btPlay = document.querySelector('#bt-play')
, player = (()=> // IIFE  for object { play(), stop() } method
  {
  let refIntv = 0, counter = 0 // inside Object values ( closure )
    ;
  function playerAction()  // inside private function
    {
    console.clear()
    console.log( 'playing', ++counter)
    }
  return {
    play()
      {
      counter = 0
      console.clear()
      console.log('start playing')
      refIntv = setInterval( playerAction , 2000)
      }
  , stop()
      {
      clearInterval( refIntv )
      console.clear()
      console.log('stop playing')
      }
    }
  })();


btPlay.onclick =_=>
  {
  if (btPlay.classList.toggle('stopped'))  player.play()
  else                                     player.stop()
  }
#bt-play { 
 margin : 1em 3em;
 width  : 5em; 
 }
#bt-play::after { 
 content : 'play';
 }
#bt-play.stopped::after { 
 content : 'stop';
 }
<button id="bt-play"></button>
<!-- control by interface : same button for start and stop -->

interface control:
if you have 2 buttons (start + stop), the user can click 2 times on the start button and you you end up with 2 overlapping interval processes (or more) without the possibility of finding the reference of the previous setInterval since this variable has been replaced to reference the process of the following interval

if not you can also add a test verifying that there is no running interval process before.

about 4 years ago · Juan Pablo Isaza Relatório

0

Details commented in example

// Reference both items
const li1 = document.getElementById("li1");
const li2 = document.getElementById("li2");

// Bind both items to click event but call different handlers
li1.addEventListener("click", start);
li2.addEventListener("click", stop);

// Declare interval ID
let y;
// Define time interval
let t = 2000;
// Define counter
let tick = 0;
// Define the function to run on each interval
const log = () => console.log(t * tick++);

// Define the event handler called from li1
function start(e) {
  // If the tag clicked was #li1 and y isn't defined yet...
  if (e.target.matches('#li1') && !y) {
    // ...Initiate interval to call log()
    y = setInterval(log, t);
  }
}
// Define the event handler called from li2
function stop(e) {
  // If user clicked #li2...
  if (e.target.matches('#li2')) {
    // ...Stop interval...
    clearInterval(y);
    // ...reset interval ID
    y = null;
  }
}
ul {
  display: flex;
  justify-content: center;
  list-style-type: none;
}

li {
  margin: 1rem;
}

li:hover {
  cursor: pointer;
}
<ul>
  <li id="li1">play</li>
  <li id="li2">stop</li>
</ul>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda